package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Layout;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;

import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.StatusBarUtils;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterConstant;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CustomException;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.RouterActivityHelper;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.immodule.Constants;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.adapter.CircleSubMemberAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase.Event_KickOffMember;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.dao.Todo;
import com.blockmeta.bbs.immodule.corebean.Impl.CircleDomainService;
import com.blockmeta.bbs.immodule.net.api.CircleDetailApi;
import com.blockmeta.bbs.immodule.net.api.DissolveCircle;
import com.blockmeta.bbs.immodule.net.api.NoDisturbCircleMsgApi;
import com.blockmeta.bbs.immodule.net.api.QuiteCircleApi;
import com.blockmeta.bbs.immodule.net.api.UpdateCircleApi;
import com.blockmeta.bbs.immodule.net.pojo.CircleDetailResponse;
import com.blockmeta.bbs.immodule.net.pojo.CircleMemberResponse;
import com.blockmeta.bbs.immodule.utils.IMUtils;
import com.blockmeta.bbs.businesslibrary.widget.CircleGradeAndKind;
import com.blockmeta.bbs.immodule.widget.PersonInfoBar;
import com.blockmeta.bbs.immodule.widget.Popup_Circle_Desc;
import com.blockmeta.bbs.immodule.widget.Popup_From_Bottom;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hellobike.flutter.thrio.navigator.ThrioNavigator;
import com.suke.widget.SwitchButton;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action0;
import rx.functions.Action1;

/**
 * @author airthor
 * @date 2019/3/26
 * 圈子详情页
 */
@Route(path = RouterPath.IM_CircleDetailActivity_ACTIVITY, extras = RouterConstant.EXTRAL_LOGIN)
public class CircleDetailActivity extends BaseActivity {

    public static final int EDIT_RESULT_CODE = 1;
    public static final int EDIT_SUCCESS = 1;
    @BindView(R2.id.iv_circle_icon)
    CircleImageView mIvCircleIcon;
    @BindView(R2.id.tv_circle_name)
    TextView mTvCircleName;
    @BindView(R2.id.cga_grade_tag)
    CircleGradeAndKind mCgaGradeTag;
    @BindView(R2.id.tv_circle_info)
    TextView mTvCircleInfo;
    @BindView(R2.id.tv_circle_size)
    TextView mTvCircleSize;
    @BindView(R2.id.rcv_members)
    RecyclerView mRcvMembers;
    @BindView(R2.id.iv_circle_silence)
    SwitchButton mTgCircleSilence;
    @BindView(R2.id.iv_circle_top)
    SwitchButton mTgCircleTop;
    @BindView(R2.id.tv_circle_limit)
    TextView mTvCircleLimit;
    @BindView(R2.id.tv_circle_verify)
    TextView mTvCircleVerify;
    @BindView(R2.id.btn_dissolve)
    Button mBtnDissolve;
    @BindView(R2.id.btn_quite)
    Button mBtnQuite;
    @BindView(R2.id.btn_join)
    Button mBtnJoin;
    @BindView(R2.id.fl_edit)
    View mEditContainer;

    @BindView(R2.id.tv_circle_options)
    TextView mTvCircleOptions;
    @BindView(R2.id.cl_circle_qr)
    ConstraintLayout mClCircleQr;
    @BindView(R2.id.cl_circle_notice)
    ConstraintLayout mClCircleNotice;
    @BindView(R2.id.cl_circle_request)
    ConstraintLayout mClCircleRequest;
    @BindView(R2.id.cl_circle_silence)
    ConstraintLayout mClCircleSilence;
    @BindView(R2.id.cl_circle_top)
    ConstraintLayout mClCircleTop;
    @BindView(R2.id.cl_member_limit)
    ConstraintLayout mClMemberLimit;
    @BindView(R2.id.cl_join_verify)
    ConstraintLayout mClJoinVerify;
    @BindView(R2.id.tv_circle_join_request)
    TextView mTvCircleJoinRequestTip;
    @BindView(R2.id.cl_member_remark)
    ConstraintLayout mClMemberRemark;
    @BindView(R2.id.tv_circle_member_remark)
    TextView mTvCircleMemberRemark;
    @BindView(R2.id.iv_arrow_circle_info)
    ImageView mIvArrowCircleInfo;
    @BindView(R2.id.llayout_personinfo_bar)
    PersonInfoBar mCircleOwnerInfoBar;


    private int mMaxItemPerLine;
    private CircleSubMemberAdapter mSubMemberAdapter;
    @Autowired(name = Constant.ZERO)
    public String ZeroParam;
    public long mCircleId;
    private CircleDetailResponse mCircleDetailResponse;
    private ArrayList<CircleMemberResponse> mMemberResponses;
    private IMUserEntity owner;
    protected boolean mIsCreate = true;
    private boolean isTriggeredByTouch = true;
    Popup_From_Bottom mPop;
    private List<String> groupLevelActions = Arrays.asList(CreateGroupInfoActivity.GROUP_LEVELS);
    private List<String> authActions = Arrays.asList(new String[]{"允许任何人", "需要加圈验证"});
    private SwitchButton.OnCheckedChangeListener topCheckedChangeListener;
    private SwitchButton.OnCheckedChangeListener silenceCheckedChangeListener;
    private int mCreateById;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_circle_detail, null);
    }

    @Override
    public void setStatusBarColor() {
        StatusBarUtils.setDarkMode(this);
        StatusBarUtils.setWindowStatusBarColor(this,R.color.status_trans);
        StatusBarUtils.setWindowFullScreen(this);
    }

    @Override
    protected void initialize() {
        super.initialize();
        IMApplicationContext.getIMMetaService().register(this);
        if (!TextUtils.isEmpty(ZeroParam)) {
            mCircleId = Long.parseLong(ZeroParam);
        } else {
            mCircleId = getIntent().getLongExtra(Params.CIRCLE_ID, 0);
        }

//        Point point = new Point();
//        getWindowManager().getDefaultDisplay().getSize(point);
//        int itemWidth = DimentionsUtil.dp2px(mContext, 52f);
        mMaxItemPerLine = 5;//point.x / itemWidth;
//        GridLayoutManager layoutManager = new GridLayoutManager(mContext, mMaxItemPerLine, GridLayoutManager.VERTICAL, false);
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, mMaxItemPerLine, GridLayoutManager.VERTICAL, false);
        mRcvMembers.setLayoutManager(layoutManager);
        mSubMemberAdapter = new CircleSubMemberAdapter(R.layout.item_sub_circle_member, null);
        mSubMemberAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mMemberResponses != null && mMemberResponses.size() > 0) {
                    CircleMemberResponse circleMemberResponse = mMemberResponses.get(position);
                    RouterActivityHelper.openUserCenter(mContext, String.valueOf(circleMemberResponse.getUserId()));
                }
            }
        });
        mRcvMembers.setAdapter(mSubMemberAdapter);

        topCheckedChangeListener = new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                mTgCircleTop.setEnabled(false);
                IMApplicationContext.getChatMessageDomainService().updateCircleStick(mCircleId, isChecked);
                IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_CircleStickUpdate(mCircleId, isChecked));
                mTgCircleTop.setEnabled(true);

            }
        };
        mTgCircleTop.setOnCheckedChangeListener(topCheckedChangeListener);
        silenceCheckedChangeListener = new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                view.setEnabled(false);
                shieldCircleMessage(mCircleId);
            }
        };
        mTgCircleSilence.setOnCheckedChangeListener(silenceCheckedChangeListener);
        netWork();
    }

    @Override
    protected void onDestroy() {
        IMApplicationContext.getIMMetaService().unregister(this);
        super.onDestroy();
    }


    @Subscribe
    public void onEvent(Event_KickOffMember event) {
        if(event.circleId == mCircleId){
            getCircleMembersData(true);
        }
    }


    @Subscribe
    public void onEvent(IMMetaBase.Event_AddMemberToCircle event) {
        if (event.groupId == mCircleId) {
            getCircleMembersData(true);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_MyCircleRemarkNameChange event){
        if(event.circleId == mCircleId){
                String myRemarkName = IMApplicationContext.getCircleDomainService().getCircleRemarkName(mCircleId);
                mTvCircleMemberRemark.setText(myRemarkName);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_EditCircles event){
        if(event.circleId == mCircleId) {
            getCircleData();
        }
    }


    /**
     * 网络请求
     */
    private void netWork() {
        ProgressBarUtil.showProgress(mContext);
        getCircleData();
    }

    private void getCircleOwnerData(final long userId, final long ownerLastMsgTime) {

        IMApplicationContext.getUserDomainService().getUser(userId, true, new BaseResponseCallBack<String, IMUserEntity>() {
            @Override
            public void fail(String msg) {
                mCircleOwnerInfoBar.setVisibility(View.GONE);
            }

            @Override
            public void success(final IMUserEntity item) {
                owner = item;
                mCircleOwnerInfoBar.onInitialize(mContext, item, mCircleId, ownerLastMsgTime, new Action0() {
                    @Override
                    public void call() {
                        showCircleDescPop();
                    }
                });
            }
        });

    }

    private void showCircleDescPop() {
        if(mCircleDetailResponse != null && owner != null){
            Popup_Circle_Desc popupCircleDesc = new Popup_Circle_Desc(mContext, mCircleDetailResponse.description
                    , owner.getSignature());
            popupCircleDesc.showPop();
        }
    }

    private void getCircleMembersData(boolean needUpdate) {
        IMApplicationContext.getCircleDomainService().getCircleMemberResponse(mContext, mCircleId, needUpdate, new Action1<List<CircleMemberResponse>>() {
            @Override
            public void call(List<CircleMemberResponse> circleMemberResponses) {
                if (circleMemberResponses == null) {
                    return;
                }
                mMemberResponses = (ArrayList<CircleMemberResponse>) circleMemberResponses;
                int size = mMemberResponses.size();
                for (int i = 0; i < size; i++) {
                    CircleMemberResponse memberRespons = mMemberResponses.get(i);
                    IMUserEntity userEntity = IMApplicationContext.getUserDomainService().getUser(memberRespons.getUserId(), Params.USER_PERSON);
                    String name = memberRespons.getName();
                    if(userEntity != null){
                        name = IMApplicationContext.getCircleDomainService()
                                .getCircleRemarkName(memberRespons.getUserId(), mCircleId, userEntity.getName(), userEntity.getRemarkName());
                    }
                    memberRespons.setName(name);
                    if (memberRespons.getUserId() == mCreateById&&i!=0){
                        Collections.swap(mMemberResponses,0,i);
                    }
                }
                //列表展示部分群成员最多两行
                int maxSize = mMaxItemPerLine * 2;
                if (circleMemberResponses.size() <= maxSize) {
                    mSubMemberAdapter.setNewData(circleMemberResponses);
                } else {
                    mSubMemberAdapter.setNewData(circleMemberResponses.subList(0, maxSize));
                }

                IMApplicationContext.getCircleDomainService().addCircleMember(circleMemberResponses);
                String myRemarkName = IMApplicationContext.getCircleDomainService().getCircleRemarkName(mCircleId);
                mTvCircleMemberRemark.setText(myRemarkName);

                mTvCircleSize.setText(String.format("%d人", circleMemberResponses.size()));

            }
        });
    }

    private void getCircleData() {
        RetrofitFactory.getRetrofit().create(CircleDetailApi.class)
                .circleDetail(mCircleId, AccountHelper.getUidInt())
                .compose(RxUtil.<BaseImResponse<CircleDetailResponse>>rxSchedulerHelper())
                .compose(RxUtil.<CircleDetailResponse>commonResult())
                .compose(this.<CircleDetailResponse>bindToLifecycle())
                .subscribe(new CommonSubscriber<CircleDetailResponse>(mContext) {
                    @Override
                    public void onNext(CircleDetailResponse circleDetailResponse) {
                        mCircleDetailResponse = circleDetailResponse;
                        handleDetailResponse(circleDetailResponse);
                        getCircleMembersData(false);
                        getCircleOwnerData(circleDetailResponse.createById, circleDetailResponse.ownerLastMsgTime);
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (t instanceof CustomException) {
                            ToastUtil.show(t.getMessage());
                        }
                    }
                });
    }

    /**
     * 处理返回的数据 展示UI
     *
     * @param circleDetailResponse 数据
     */

    private void handleDetailResponse(final CircleDetailResponse circleDetailResponse) {
        mCreateById = circleDetailResponse.createById;
        //群头像
        LoadPicUtil.loadWithPicasso(mIvCircleIcon, circleDetailResponse.groupLogo);
        mTvCircleName.setText(circleDetailResponse.name);
        mCgaGradeTag.setText(circleDetailResponse.groupLevel + "", "群组");
        mTvCircleInfo.setText(circleDetailResponse.description);

        ViewTreeObserver vto = mTvCircleInfo.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Layout l = mTvCircleInfo.getLayout();
                if (l != null) {
                    int lines = l.getLineCount();
                    if (lines > 0) {
                        if (l.getEllipsisCount(lines - 1) > 0) {
                            mIvArrowCircleInfo.setVisibility(View.VISIBLE);
                            mIvArrowCircleInfo.setOnClickListener(new View.OnClickListener(){
                                @Override
                                public void onClick(View v) {
                                    showCircleDescPop();
                                }
                            });
                        }else{
                            mIvArrowCircleInfo.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });

        boolean joinState = circleDetailResponse.isMeIn;
        boolean isCreator = AccountHelper.getUidInt() == circleDetailResponse.createById;
        //根据用户不同的圈子身份 显示隐藏一些UI
        mEditContainer.setVisibility(isCreator ? View.VISIBLE : View.INVISIBLE);
        //加入圈子按钮 当用户为游客时显示 其它隐藏
        mBtnJoin.setVisibility(joinState ? View.GONE : View.VISIBLE);
        //解散圈子 当用户为有此权限的人（目前指创建者）显示 其它隐藏
        mBtnDissolve.setVisibility(isCreator ? View.VISIBLE : View.GONE);
        //退出圈子 当用户为圈子成员但不是创建者时显示 其它隐藏
        mBtnQuite.setVisibility(isCreator ? View.GONE : joinState ? View.VISIBLE : View.GONE);
        //圈子选项的分割标题 当用户为加圈时不显示
        mTvCircleOptions.setVisibility(View.VISIBLE);
//        mClCircleQr.setVisibility(View.VISIBLE);
//        mClCircleNotice.setVisibility(isCreator ? View.VISIBLE : View.GONE);
        //加圈请求项 当用户非圈子成员非管理员时隐藏
        mClCircleRequest.setVisibility(isCreator ? View.VISIBLE : View.GONE);
        //备注自己圈中昵称
//        mClMemberRemark.setVisibility(joinState ? View.VISIBLE : View.GONE);
        //群消息免打扰 当用户非圈子成员时隐藏
        mClCircleSilence.setVisibility(joinState ? View.VISIBLE : View.GONE);
        //群置顶 当用户非圈子成员时隐藏
        mClCircleTop.setVisibility(joinState ? View.VISIBLE : View.GONE);
        //群验证是否开启选项 当用户非管理员时隐藏
        mClJoinVerify.setVisibility(View.GONE);
        //加圈限制选项 当用户非管理员时隐藏
        mClMemberLimit.setVisibility(View.GONE);

        mTvCircleLimit.setText(IMUtils.getLimitGrade(circleDetailResponse.userLevel));
        mTvCircleVerify.setText(authActions.get(circleDetailResponse.authRule));

        switchToggle(circleDetailResponse.noDisturbing ? true : false, mTgCircleSilence, silenceCheckedChangeListener);

        if(AccountHelper.isLogin()){
            boolean stick = IMApplicationContext.getChatMessageDomainService().getCircleStick(mCircleId, ChatMessage.MSG_TYPE_UCG);
            //默认是不选中，如果需要选中需要设置isTriggeredByTouch为false
            switchToggle(stick, mTgCircleTop, topCheckedChangeListener);
        }

        if (isCreator) {
            bindCircleRequestTip();
        }

    }

    private void switchToggle(boolean stick, SwitchButton switchButton, SwitchButton.OnCheckedChangeListener listener) {
        switchButton.setOnCheckedChangeListener(null);
        switchButton.setChecked(stick);
        switchButton.setOnCheckedChangeListener(listener);
    }

    /**
     * 查询时候有该圈子的加圈申请,如果点击过就不再显示
     */
    private void bindCircleRequestTip() {
        //获取上次进入查看后最后一条todo的时间，如果和当前的时间相同就不显示红点
        Todo circleLasteatUnCompleteTodo = IMApplicationContext.getTodoDomainService().getCircleLasteatUnCompleteTodo(mCircleId, AccountHelper.getUidInt());
        Long lastToDoTime = SharedPreferenceUtil.getLong(mContext, Constants.CIRCLE_LASTTODO_TIME + mCircleId, 0);
        if (circleLasteatUnCompleteTodo != null && circleLasteatUnCompleteTodo.getCreateDate() > lastToDoTime) {
            mTvCircleJoinRequestTip.setVisibility(View.VISIBLE);
        } else {
            mTvCircleJoinRequestTip.setVisibility(View.GONE);
        }
    }

    @OnClick({R2.id.fl_back, R2.id.fl_edit, R2.id.cl_circle_member, R2.id.cl_circle_qr, R2.id.cl_circle_request
            , R2.id.cl_member_limit, R2.id.cl_join_verify, R2.id.btn_dissolve, R2.id.btn_quite, R2.id.btn_join, R2.id.cl_member_remark
            , R2.id.cl_circle_notice,R2.id.cl_circle_list
    })
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();

        } else if (i == R.id.fl_edit) {//编辑
            if (mCircleDetailResponse == null) {
                return;
            }
            Intent eqIntent = new Intent(this, EditGroupInfoActivity.class);
            eqIntent.putExtra(Params.CIRCLE_DETAIL, mCircleDetailResponse);
            startActivity(eqIntent);

        } else if (i == R.id.cl_circle_member) {//圈子成员
            if (mMemberResponses == null) {
                return;
            }
            Intent memberIntent = new Intent(mContext, CircleMembersActivity.class);
            memberIntent.putExtra(Params.MEMBERS, mMemberResponses);
            if (mCircleDetailResponse != null) {
                memberIntent.putExtra(Params.ISMANGER, AccountHelper.getUidInt() == mCircleDetailResponse.createById);
            }
            startActivity(memberIntent);

        } else if (i == R.id.cl_circle_qr) {//圈子二维码
            if (mCircleDetailResponse == null) {
                return;
            }
            Intent qrIntent = new Intent(this, CircleQrCodeActivity.class);
            qrIntent.putExtra(Params.CIRCLE_DETAIL, mCircleDetailResponse);
            startActivity(qrIntent);
        } else if(i == R.id.cl_circle_notice){
            if(mCircleDetailResponse == null){
                return;
            }
            Intent qrIntent = new Intent(this, CircleNoticeActivity.class);
            boolean isCreator = AccountHelper.getUidInt() == mCircleDetailResponse.createById;
            qrIntent.putExtra(Params.IS_CIRCLE_CREATER, isCreator);
            qrIntent.putExtra(Params.CIRCLE_ID, mCircleId);
            startActivity(qrIntent);

        } else if (i == R.id.cl_circle_request) {//加圈请求
            startActivity(new Intent(mContext, JoinCircleRequestsActivity.class).putExtra(Constants.CIRCLE_ID, mCircleId));
            mTvCircleJoinRequestTip.setVisibility(View.GONE);

        } else if (i == R.id.cl_member_limit) {//加圈等级限制
            mPop = new Popup_From_Bottom(mContext, getWindow().getDecorView(), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ProgressBarUtil.showProgress(mContext);
                    HashMap<String, String> params = new HashMap<>();
                    params.put("chatGroupId", String.valueOf(mCircleDetailResponse.id));
                    params.put("userId", String.valueOf(AccountHelper.getUidInt()));
                    params.put("user_level", String.valueOf(position));

                    RetrofitFactory.getRetrofit().create(UpdateCircleApi.class)
                            .updateChatGroup(params)
                            .compose(RxUtil.<BaseImResponse<CircleDetailResponse>>rxSchedulerHelper())
                            .compose(RxUtil.<CircleDetailResponse>commonResult())
                            .compose(CircleDetailActivity.this.<CircleDetailResponse>bindToLifecycle())
                            .subscribe(new CommonSubscriber<CircleDetailResponse>(mContext) {
                                @Override
                                public void onNext(CircleDetailResponse circleDetailResponse) {
                                    LogUtils.i("author" + "edit user_level success");
                                    mTvCircleLimit.setText(IMUtils.getLimitGrade(circleDetailResponse.userLevel));
                                }
                            });
                    mPop.dismiss();
                }
            }, groupLevelActions, new Popup_From_Bottom.OnDismissListener() {
                @Override
                public void onDismissListener() {

                }
            });


            mPop.show();

        } else if (i == R.id.cl_join_verify) {//加圈验证
            mPop = new Popup_From_Bottom(mContext, getWindow().getDecorView(), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    ProgressBarUtil.showProgress(mContext);
                    HashMap<String, String> params = new HashMap<>();
                    params.put("chatGroupId", String.valueOf(mCircleDetailResponse.id));
                    params.put("userId", String.valueOf(AccountHelper.getUidInt()));
                    params.put("auth_rule", String.valueOf(position > 0 ? 1 : 0));

                    RetrofitFactory.getRetrofit().create(UpdateCircleApi.class)
                            .updateChatGroup(params)
                            .compose(RxUtil.<BaseImResponse<CircleDetailResponse>>rxSchedulerHelper())
                            .compose(RxUtil.<CircleDetailResponse>commonResult())
                            .compose(CircleDetailActivity.this.<CircleDetailResponse>bindToLifecycle())
                            .subscribe(new CommonSubscriber<CircleDetailResponse>(mContext) {
                                @Override
                                public void onNext(CircleDetailResponse circleDetailResponse) {
                                    LogUtils.i("author" + "edit authRule success");
                                    mTvCircleVerify.setText(authActions.get(position));
                                }
                            });
                    mPop.dismiss();
                }
            }, authActions, new Popup_From_Bottom.OnDismissListener() {
                @Override
                public void onDismissListener() {

                }
            });


            mPop.show();

        } else if (i == R.id.btn_dissolve) {//解散圈子
            dissolveCircle();

        } else if (i == R.id.btn_quite) {//退出圈子
            quiteCircle();

        } else if (i == R.id.btn_join) {//加入圈子
            joinCircle();

        } else if (i == R.id.cl_member_remark) {//修改备注
            Intent remarkIntent = new Intent(mContext, RemarksActivity.class);
            remarkIntent.putExtra(Params.CIRCLE_ID, mCircleId);
            String myRemarkName = IMApplicationContext.getCircleDomainService().getCircleRemarkName(mCircleId);
            remarkIntent.putExtra(Params.MYCIRCLEREMARK, myRemarkName);
            startActivity(remarkIntent);
        } else if(i == R.id.cl_circle_list){
            Map<String, Integer> map = new HashMap<>();
            map.put("groupId", (int)mCircleId);
            Log.d("flutterting", "open group activity page");
            ThrioNavigator.push("/activity/groupList",
                    map,
                    true,
                    (v) -> {
                        return null;
                    }
            );

        }
    }


    /**
     * 消息免打扰
     *
     * @param circleId 圈子ID
     */
    private void shieldCircleMessage(long circleId) {
        ProgressBarUtil.showProgress(mContext);

        RetrofitFactory.getRetrofit().create(NoDisturbCircleMsgApi.class)
                .noDisturbChatGroup(circleId, AccountHelper.getUidInt())
                .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                .compose(RxUtil.commonResult())
                .compose(bindToLifecycle())
                .subscribe(new CommonSubscriber<Object>(mContext) {
                    @Override
                    public void onNext(Object o) {
                        IMApplicationContext.getCircleDomainService().setNoDisturb(mCircleId, mTgCircleSilence.isChecked());
                        mTgCircleSilence.setEnabled(true);


                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        switchToggle(!mTgCircleSilence.isChecked(), mTgCircleSilence, silenceCheckedChangeListener);
                        mTgCircleSilence.setEnabled(true);
                    }
                });
    }

    /**
     * 解散圈子
     */
    private void dissolveCircle() {
        ProgressBarUtil.showProgress(mContext);
        RetrofitFactory.getRetrofit().create(DissolveCircle.class)
                .dissolveCircle(mCircleId, AccountHelper.getUidInt())
                .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                .compose(RxUtil.commonResult())
                .compose(bindToLifecycle())
                .subscribe(new CommonSubscriber<Object>(mContext) {
                    @Override
                    public void onNext(Object o) {
                        IMApplicationContext.getCircleDomainService().deleteCircle(mCircleId);
                        IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_DeleteCircles());
                        finish();
                    }
                });
    }

    /**
     * 退出圈子
     */
    public void quiteCircle() {
        ProgressBarUtil.showProgress(mContext);
        RetrofitFactory.getRetrofit().create(QuiteCircleApi.class)
                .quiteCircle(mCircleId, AccountHelper.getUidInt())
                .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                .compose(RxUtil.commonResult())
                .compose(bindToLifecycle())
                .subscribe(new CommonSubscriber<Object>(mContext) {
                    @Override
                    public void onNext(Object o) {
                        IMApplicationContext.getCircleDomainService().deleteCircle(mCircleId);
                        IMApplicationContext.getChatMessageDomainService().deleteCircleChatMessage(AccountHelper.getUidInt(), mCircleId);
                        IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_Comment_Data(Params.IMEvent_Quit_Circle, mCircleId));
                        IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_DeleteCircles());
                        finish();
                    }
                });
    }


    /**
     * 申请加圈
     */
    private void joinCircle() {
        if (mCircleDetailResponse == null) {
            return;
        }
        IMApplicationContext.getCircleDomainService().joinCircle(mContext, mCircleId, mCircleDetailResponse.authRule, mCircleDetailResponse.userLevel, new CircleDomainService.CircleJoinCallBack() {

            @Override
            public void onSuccess(String message) {
                ToastUtil.show("加入成功");
                //本地更新加入状态
                RouterHelper.startActivity(mContext
                        , RouterPath.IM_UCGChatActivity_ACTIVITY, String.valueOf(mCircleId));
            }

            @Override
            public void onFail() {

            }
        });
    }

}
